local mysql = require "model.mysql"
local domain_model = {}

function domain_model.addDomain(name, domain_name)
    local db = mysql.getDb()
    if domain_name ~= nil and domain_name ~= '' then
        local count, err, a1, a2 = db:query("select id from agw_domain where domain_name=\'" .. domain_name .. "\'", 10)
        if count and table.getn(count) > 0 then
           return {}, '名称重复'
        end
    end

    local res, err, _, _ = db:query("INSERT INTO agw_domain (name,domain_name) values(\'" .. name .. "\',\'" .. domain_name .. "\')", 10)
    db:set_keepalive(10000, 100)
    return res, err
end

function domain_model.delete(id)
    local db = mysql.getDb()
    local res, err, _, _ = db:query("DELETE FROM agw_domain WHERE id=" .. id, 10)
    db:set_keepalive(10000, 100)
    return res, err
end

function domain_model.update(id, name,domain_name)
    local db = mysql.getDb()

    if domain_name ~= nil and domain_name ~= '' then
        local count, err, a1, a2 = db:query("select id from agw_domain where domain_name=\'" .. domain_name .. "\' and id != " .. id, 10)
        if count and table.getn(count) > 0 then
            return {}, '名称重复'
        end
    end

    local res, err, _, _ = db:query("UPDATE agw_domain SET name=\'" .. name .. "\',domain_name=\'" .. domain_name .. "\' WHERE id=" .. id, 10)
    db:set_keepalive(10000, 100)
    return res, err
end

function domain_model.getDomain(id)
    local db = mysql.getDb()
    local service, err, _, _ = db:query("SELECT * FROM agw_domain WHERE id=" .. id, 10)
    db:set_keepalive(10000, 100)
    return service, err
end

function domain_model.getDomains()
    local db = mysql.getDb()
    local res, err, _, _ = db:query("SELECT * FROM agw_domain ORDER BY id ASC", 10)
    db:set_keepalive(10000, 100)
    return res, err
end

function domain_model.getDomainsNotEmpty()
    local db = mysql.getDb()
    local res, err, _, _ = db:query("SELECT * from agw_domain where domain_name is not null and domain_name!=''", 10)
    db:set_keepalive(10000, 100)
    return res, err
end

return domain_model
